/*
 ** money check 投保金额校验
 **
 ** 校验规则：
 ** 1、符合金额规则
 ** 2、整数倍数（可选）
 **
 */

(function() {
	'use strict';

	angular
		.module('elife')
		.directive('moneyCheck', moneyCheck);

	moneyCheck.$inject = ['VALIDATION'];
	/** @ngInject */
	function moneyCheck(VALIDATION) {
		var directive = {
			restrict: 'A',
			require: 'ngModel',
			link: linkFunc
		};

		return directive;

		function linkFunc(scope, elem, attr, ngModel) {

			var checkMoney = function(value){
				if (!value) {
					ngModel.$setValidity('invalid', true);
					ngModel.$setValidity('format', true);
					ngModel.$setValidity('min', true);
					ngModel.$setValidity('max', true);
					return;
				}

				if (!VALIDATION.moneyCheck(value)) {
					ngModel.$setValidity('invalid', false);
				} else {
					ngModel.$setValidity('invalid', true);

					var multiple = attr.multi;
					if (multiple) {
						if (!VALIDATION.multipleCheck(value, multiple)) {
							ngModel.$setValidity('format', false);
							ngModel.$setValidity('min', true);
							ngModel.$setValidity('max', true);
						} else {
							ngModel.$setValidity('format', true);

							checkMin();
							checkMax();
						}
					} else {
						checkMin();
						checkMax();
					}
				}

				function checkMin() {
					var min = attr.min;
					if (min && parseFloat(min) > parseFloat(value)) {
						ngModel.$setValidity('min', false);
					} else {
						ngModel.$setValidity('min', true);
					}
				}

				function checkMax() {
					var max = attr.max;
					if (max && parseFloat(max) < parseFloat(value)) {
						ngModel.$setValidity('max', false);
					} else {
						ngModel.$setValidity('max', true);
					}
				}

			}

			scope.$watch(attr.ngModel, function(value) {
				checkMoney(value);
			});

			scope.$watch(attr.minBuyQautity, function() {
				var value = attr.value;
				if(value){
					checkMoney(value);
				}

			});

			scope.$watch(attr.maxBuyQautity, function() {
				var value = attr.value;
				if(value){
					checkMoney(value);
				}
			});
		}
	}
})();
